package com.uxwine.audio;

import com.uxwine.alarm.R;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;

public class AudioEffect {
	
	private Context mCtx;
	private SoundPool mSoundPool;
	private int[] mSounds;
	private AudioManager mAudioManager;
	private int mnMaxVolume;
	private boolean mbSilent;
	
	private static AudioEffect mInstance;
	
	public synchronized static AudioEffect getInstance(Context ctx)
	{
		if(null == mInstance)
		{
			mInstance = new AudioEffect(ctx);
		}
		return mInstance;
	}
	
	private AudioEffect(Context ctx)
	{
		mCtx = ctx.getApplicationContext();
		mSounds = new int[2];
		mAudioManager = (AudioManager) mCtx.getSystemService(Context.AUDIO_SERVICE);
		mnMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);
		mbSilent = false;
	}
	
	private int getCurrentVolume()
	{
		return mAudioManager.getStreamVolume(AudioManager.STREAM_SYSTEM);
	}
	
	private float getVolume()
	{
		if(mbSilent)
			return 0.0f;
		return (float)((float)getCurrentVolume() / (float)mnMaxVolume);
	}
	
//	private MediaPlayer mPlayer;
//	private String path;

	public boolean play(int id) {
		
		if(id < 0 || id >= mSounds.length)
			return false;
		
		float v = getVolume();
		mSoundPool.play(mSounds[id], v, v, 0, 0, 1);	
		return true;
		
//		MediaPlayer mediaPlayer = new MediaPlayer();
//		if (mediaPlayer != null) {
//			try {
//				String filePath = Environment.getRootDirectory()
//						+ SOUND_EFFECTS_PATH
//						+ SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effectType][0]];
//				mediaPlayer.setDataSource(filePath);
//				mediaPlayer.setAudioStreamType(AudioSystem.STREAM_RING);
//				mediaPlayer.prepare();
//				mediaPlayer.setVolume(volFloat, volFloat);
//				mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
//					public void onCompletion(MediaPlayer mp) {
//						cleanupPlayer(mp);
//					}
//				});
//				mediaPlayer.setOnErrorListener(new OnErrorListener() {
//					public boolean onError(MediaPlayer mp, int what, int extra) {
//						cleanupPlayer(mp);
//						return true;
//					}
//				});
//				mediaPlayer.start();
//			} catch (IOException ex) {
//				Log.w(TAG, "MediaPlayer IOException: " + ex);
//			} catch (IllegalArgumentException ex) {
//				Log.w(TAG, "MediaPlayer IllegalArgumentException: " + ex);
//			} catch (IllegalStateException ex) {
//				Log.w(TAG, "MediaPlayer IllegalStateException: " + ex);
//			}
//		}
	}
	
	public void init()
	{
		mSoundPool = new SoundPool(2, AudioManager.STREAM_SYSTEM, 0);
		mSounds[0] = mSoundPool.load(mCtx, R.raw.marked, 0);
		mSounds[1] = mSoundPool.load(mCtx, R.raw.btn, 0);		
	}
	
	public void uninit()
	{
		mSoundPool.unload(mSounds[0]);
		mSoundPool.unload(mSounds[1]);
	}

	@Override
	protected void finalize() throws Throwable {
		uninit();
	}
	
	

	// private class EventListener imp
}
